#include<malloc.h>
#include<string.h>


/*
  This function takes a string 'str' and parses this string in various sub-strings depending on the seperation char 'c',
  'start', and 'end'. The sub-strings are returned.

  Example:

     char **s; short n;

     s = parse_int("  abababa   hshshshshs    jkjkjkjk uyuyuyuy ", ' ', 2, 6, &n);

   It will return:
        s[0] = "hshshshshs",
        s[1] = "jkjkjkjk",
        s[2] = "uyuyuyuy",
        s[3] = (char *)0 i.e. null pointer;
        s[4] and s[5]: doesn't exist;
        n = 3;
*/

extern char **parse_str(const char *str, char c, unsigned short start, unsigned short end, unsigned short *nsubs)
{
 int i, j, k, l, flag, count, n;
 char **s;
 struct span {int i, l;} *token;


 if(start > end) return (char **)0;

 n = end - start + 1;

 token = (struct span *)malloc(n*sizeof(struct span));

 l = strlen(str);

 for(count = flag = i = j = k = 0; i < l; i++)
    {
     if(str[i] != c)
        {
         if(flag == 0) count++;
         if((count >= start)&&(count <= end)) if(k++ == 0) token[j].i = i;
         flag = 1;
        }

    if(flag == 1) if((str[i] == c)||(i == l-1))
       {
        if((count >= start)&&(count <= end))
           {
            token[j++].l = k;
            if(j == n) break;
            k = 0;
           }
        flag = 0;
       }
   }

 s = (char **)malloc(sizeof(void *)*j);
//printf("------j = %d\n",j);
 for(i = 0; i < j; i++)
     {
      s[i] = (char *)malloc(sizeof(char)*(token[i].l + 1));
      strncpy(s[i], str + token[i].i, token[i].l);
      s[i][token[i].l] = '\0';
     }

 if(nsubs != (unsigned short *)0) *nsubs = (unsigned short)j;
 free(token);

 return s;
}
